#include "WordsSolitaire.h"

#include <QMessageBox>

#include <spdlog/spdlog.h>

WordsSolitaire::WordsSolitaire()
{
    wordCache = WordCache::Create();
    wordReport = WordReport::Create();
    wordCache->SetReport(wordReport);

    // 创建输入区域（QLineEdit）
    //inputLineEdit = new QLineEdit(this);
    inputLineEdit = std::make_shared<QLineEdit>(this);
    inputLineEdit->setPlaceholderText("请输入单词");

    textEdit = std::make_shared<QPlainTextEdit>(this);
    textEdit->setReadOnly(true);

    countdownWidget = std::make_shared<CountdownWidget>(1200);

    calculateButton = std::make_shared<QPushButton>("计算", this);
    clearButton = std::make_shared<QPushButton>("清除", this);

    // 创建水平布局管理器
    mainLayout = std::make_shared<QHBoxLayout>();

    // 创建一个用于放置输入框的垂直布局管理器
    leftLayout = std::make_shared<QVBoxLayout>();   

    leftLayout->addWidget(calculateButton.get());
    leftLayout->addWidget(clearButton.get());
    leftLayout->addWidget(countdownWidget.get());
    leftLayout->addWidget(inputLineEdit.get());

    // 将垂直布局管理器添加到水平布局管理器左边
    mainLayout->addLayout(leftLayout.get());

    // 设置展示区域（QLabel）的大小策略
    QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    sizePolicy.setHorizontalStretch(3);
    textEdit->setSizePolicy(sizePolicy);


    // 将展示区域添加到水平布局管理器右边
    mainLayout->addWidget(textEdit.get());
    this->setLayout(mainLayout.get());

    // 连接信号与槽，当在QLineEdit中输入内容并按下回车键时，更新展示区域的内容
    connect(inputLineEdit.get(), &QLineEdit::returnPressed, this, [this]() {
        QString inputText = inputLineEdit->text();
        inputLineEdit->clear();
        int result = wordCache->AddWord(inputText.toStdString());
        if(result == WordCache::ADD_ERROR_DUPLICATED){
            QMessageBox::warning(this, "错误", "重复单词");
            return;
        }else if(result == WordCache::ADD_ERROR_WRONG){
            QMessageBox::warning(this, "错误", "单词不存在");
            return;
        }
        textEdit->appendPlainText(inputText);
    });

    connect(calculateButton.get(), &QPushButton::clicked, this, [this](){
        textEdit->clear();
        wordReport->Calculate(wordCache->GetWords());
        textEdit->appendPlainText(QString::fromStdString(wordReport->GetSummary()));
    });

    connect(clearButton.get(), &QPushButton::clicked, this, [this](){
        textEdit->clear();
        wordCache->Clear();
        wordReport->Clear();
    });
}

WordsSolitaire::~WordsSolitaire()
{
    SPDLOG_TRACE("~WordsSolitaire()");
}